<template>
    <!--预催收 待分配订单-->
    <div class="content_panel project_modules">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('collection.waitAssignList')}}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row>
                    <el-col :span="4">
                        <el-form-item prop="orderId" label="">
                            <el-input v-model="form.orderId" :placeholder="$t('common.innerOrderId')" clearable></el-input><!--内部订单号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="phone" label="">
                            <el-input v-model="form.phone" :placeholder="$t('common.mobileNumber')" clearable></el-input><!--手机号码-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userId" label="">
                            <el-input v-model="form.userId" placeholder="User ID" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" v-if="domain!='Bene'">
                        <el-form-item prop="repayGrade" >
                            <el-input v-model.number="form.repayGrade" :placeholder="$t('common.overdueDays')" clearable></el-input><!--逾期天数-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="productChannel" label="">
                            <el-input v-model="form.productChannel" :placeholder="$t('common.applicationMarket')" clearable></el-input><!--应用市场-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="source" label="">
                            <el-input v-model="form.source" :placeholder="$t('common.applyChannel')" clearable></el-input><!--申请渠道-->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appVersion" label="">
                            <el-input v-model="form.appVersion" :placeholder="$t('common.versionName')" clearable></el-input><!--版本号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="appPackage" label="">
                            <el-input v-model="form.appPackage" :placeholder="$t('system.appPackage')" clearable></el-input><!--app包名-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="applyTime" label=""><!--申请时间-->
                            <el-date-picker
                                    style="width:100%"
                                    v-model="form.applyTime"
                                    type="datetimerange"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="timestamp"
                                    :editable="false"
                                    range-separator="-"
                                    :default-time="['00:00:00', '23:59:59']"
                                    :start-placeholder="$t('common.applyStartTime')"
                                    :end-placeholder="$t('common.applyEndTime')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userType" > <!--用户类型-->
                            <el-select v-model="form.userType" :clearable='true' :placeholder="$t('common.userType')" style="width: 100%">
                                <el-option key="0" :label="$t('common.newUser')" value="0"></el-option>
                                <el-option key="1" :label="$t('common.secNewUser')" value="1"></el-option>
                                <el-option key="2" :label="$t('common.oldUser')" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <!-- 伪名 -->
                    <el-col :span="4">
                        <el-form-item prop="whiteProductName" v-if="domain == 'Bene'"> <!---->
                            <el-input v-model="form.whiteProductName" :placeholder="$t('common.productName')" clearable><!----></el-input>
                        </el-form-item>
                        <el-form-item v-else prop="kana"> <!--姓名-->
                            <select-kana-list v-model="form.kana" :multiple="false" :placeholder="$t('finance.pseudonym')"></select-kana-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                        <el-button @click="exportData" type="primary">{{ $t('common.export') }}</el-button>
                        <el-button @click="assignOrder" :disabled="!selectedList || selectedList.length <= 0" type="primary" class="recheck_batch">{{ $t('common.handAssignOrder') }}</el-button>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item>
                            <el-switch
                                v-model="autoAssignOrde.isOpen"
                                :active-text="$t('common.openAssignOrder')"
                                :inactive-text="$t('common.closeAssignOrder')" @change="changeAutoAssignOrder">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->
        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table ref="table" :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" @selection-change="selectionChange" :highlight-current-row="true">
                        <el-table-column type="selection"></el-table-column>
                        <el-table-column prop="orderId" :label="$t('common.innerOrderId')" width="180"><!--内部订单号-->
                            <template slot-scope="{ row }">
                                <a @click="goDetail(row)" type="text" size="small" v-if="row.orderId" href="javascript:void(0);">{{ row.orderId }}</a>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userId" label="User ID" min-width="100"></el-table-column>
                        <el-table-column prop="userType" :label="$t('common.userType')" width="150"><!--用户类型-->
                            <template slot-scope="scope">
                                <span>{{ scope.row.userType | switchUserType }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userName" :label="$t('common.name')" min-width="150"></el-table-column><!--姓名-->
                        <el-table-column prop="phone" :label="$t('common.mobileNumber')" min-width="120"></el-table-column><!--手机号-->
                        <el-table-column prop="cardId" :label="$t('common.idCardNumber')" min-width="150"></el-table-column><!--身份证号-->
                        <el-table-column prop="loanTime" :label="$t('common.applyDate')" min-width="160"><!--申请日期-->
                            <template slot-scope="{ row }">{{ row.loanTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <el-table-column prop="contractAmount" :label="$t('common.contractAmount')" width="100"><!--借款金额-->
                            <template slot-scope="{ row }">
                                <el-button  v-if="domain=='Bene'" type="text" @click="showSpreadDialog(row)">{{ row.contractAmount | formatCurrency }}</el-button>
                                <div v-else>{{ row.contractAmount | formatCurrency }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="periodDays" :label="$t('common.borrowingCycle')" min-width="100"><!--借款周期-->
                            <template slot-scope="{ row }">{{ row.periodDays }}{{ $t('common.day') }}</template>
                        </el-table-column>
                        <el-table-column prop="lateRepay" :label="$t('common.shouldRepayAmount')" width="100"><!--应还金额-->
                            <template slot-scope="{ row }">{{ row.lateRepay | formatCurrency }}</template>
                        </el-table-column>
                        <el-table-column align="left" :label="$t('common.shouldRepayTime')" min-width="170" prop="repayTime"><!--应还时间-->
                            <template slot-scope="{ row }" >
                                <el-button v-if="domain=='Bene'" type="text" @click="showSpreadDialog(row)">{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</el-button>
                                <template v-else>{{ row.repayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalPeriods" v-if="showSpread" :label="$t('install.totalBorrowPeriod')" min-width="150"></el-table-column><!--借款总周期-->
                        <el-table-column prop="period" v-if="showSpread" :label="$t('install.currentBorrowPeriod')" min-width="150"></el-table-column><!--借款当前周期-->

                        <el-table-column prop="repayGrade" :label="$t('common.overdueDays')" min-width="100">
                            <template slot-scope="{ row }">
                                <div v-if="domain=='Bene'">
                                    <el-button type="text" @click="showSpreadDialog(row)">{{ row.repayGrade}}</el-button>
                                </div>
                                <div v-else slot-scope="{ row }">{{ row.repayGrade }}</div>
                            </template>
                        </el-table-column><!--逾期天数-->
                        
                        <el-table-column align="left" :label="$t('common.applicationMarket')" prop="productChannel" width="130"></el-table-column><!--应用市场-->
                        <el-table-column :label="$t('common.applyChannel')" prop="source" min-width="130"></el-table-column><!--申请渠道-->
                        <el-table-column :label="$t('system.appName')" prop="appName" min-width="130">
                            <template slot-scope="{ row }">{{ row.appName | switchAppName }}</template>
                        </el-table-column><!--APP名称-->
                        <el-table-column v-if="domain=='Bene'" :label="$t('finance.productName')" prop="whiteProductName" min-width="130"></el-table-column><!--伪名-->
                        <el-table-column v-else :label="$t('finance.pseudonym')" prop="kana" min-width="130">
                            <template slot-scope="{ row }">{{ row.kana | switchProductName }}</template>
                        </el-table-column><!--伪名-->

                        <el-table-column :label="$t('common.versionName')" prop="appVersion" min-width="130"></el-table-column><!--版本号-->
                        <el-table-column :label="$t('system.appPackage')" prop="appPackage" min-width="130"></el-table-column><!--APP包名-->
                    </el-table>
                    <!--分页组件-->
                    <section class="pagination" v-show="page.recordsTotal">
                        <el-pagination background @current-change="pageChange" @size-change="handleSizeChange" :current-page="page.currentPage" :page-sizes="[20, 50]" :page-size="page.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="page.recordsTotal">
                        </el-pagination>
                    </section>
                </div>
            </div>
        </div>
         <!--手动分单弹框-->
        <el-dialog :visible.sync="assignOrderDialog.isVisible" width="600px" :title="$t('common.handAssignOrder')">
            <el-form :model="assignOrderDialog.groupForm" label-position="top">
                <el-form-item>
                    <el-radio-group v-model="assignOrderDialog.groupForm.operator" style="width: 100%;">
                        <el-row>
                            <el-col v-for="item in staffList" :key="item.collectionUserId" :span="12">
                                <el-radio style="margin-bottom: 10px;" :label="item.collectionUserId">{{ item.collectionUserName }}</el-radio>
                            </el-col>
                        </el-row>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAssignOrder" :disabled="!assignOrderDialog.groupForm.operator">{{$t('common.submit')}}</el-button>
                <el-button type="default" @click="cancel">{{$t('common.cancel')}}</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync = 'SpreadListObj.isVisible' width="70%">
            <spreadListDialog type="pre" v-if="SpreadListObj.isVisible" :rowData="SpreadListObj.data"/>
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="()=>SpreadListObj.isVisible=false">{{$t('common.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import SelectAppList from '@/components/select-app-list';
    import {domain} from '@/config/'
    import SelectKanaList from '@/components/select-kana-list';
    import spreadListDialog from '../../components/spread-list-Dialog'
    export default {
        name: 'collection-preOrderManage-waitAssign',
        components: {
            // Pagination,
            SelectAppList,
            SelectKanaList,
            spreadListDialog
        },
        mixins: [mixin],
        data() {
            const checkGrade = (rule, value, callback) => {
                if(value > 999 || value < -10) {
                    return callback(this.$t('collection.plsInputRightOverday'));
                }
                else {
                    callback();
                }
            };
            return {
                SpreadListObj:{
                    isVisible:false,
                    data:{},
                },
                domain:'',
                showSpread:false,
                user: this.$storage.get('user'),
                form: {
                    orderId: '',
                    userType: '',
                    phone: '',
                    repayGrade: '',
                    userId: '',
                    productChannel: '',
                    source: '',
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                    appVersion: '',
                    appPackage: '',
                    applyTime: [],
                },
                rules: {
                    orderId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    phone: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    userId: [
                        {pattern: /^\d+$/, message: this.$t('verify.plsInputNumber')},
                    ],
                    repayGrade: [
                        {pattern: /^-?[0-9]\d*$/, message: this.$t('collection.plsInputRightOverday'), trigger: 'blur'},
                        { validator: checkGrade, trigger: 'blur' }
                    ],
                    applyTime: []
                },
                selectedList: [],
                assignOrderDialog: {
                    isVisible: false,
                    groupForm: {
                        operator: '',
                    },
                },
                staffList: [],
                autoAssignOrde: {
                    isOpen: '',
                    id: ''
                },
            };
        },
        methods: {
            showSpreadDialog(row){
                this.SpreadListObj = {
                    isVisible:true,
                    data:row
                }
            },
            // 获取列表数据
            getTableData(page = this.page) {
                const params = this.fillParams(page);
                this.$api.collection.queryNoAssignOrder(params).then(res => {
                    const {status, data, error} = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                    }
                    this.tableMaxHeight = document.body.clientHeight - 325;
                });
            },
            // 搜索列表数据
            search() {
                this.$refs.form.validate(val => {
                    if (val) {
                        this.page.currentPage = 1;
                        this.getTableData();
                    }
                });
            },
            // 导出列表数据
            exportData() {
                this.$refs.form.validate(val => {
                    if (val) {
                        const params = this.fillParams();
                        const user = this.$storage.get('user');
                        const language = this.$storage.getLocal('language');
                        params.language = language;
                        params.token = user.token;
                        params.source = encodeURIComponent(params.source); //针对特殊渠道转码
                        const {$apiConf} = this;
                        const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.collection.exprotNoAssignOrderExcel, ['page']);
                        this.$openNewBlank(url);
                    }
                });
            },
            // 配置查询和导出参数
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    orderId: form.orderId,
                    phone: form.phone,
                    repayGrade: form.repayGrade,
                    userId: form.userId,
                    userType: form.userType,
                    lstartTime: '',
                    lendTime: '',
                    collectionUserId: this.user.id,
                    productChannel: form.productChannel,
                    source: form.source,
                    appName: form.appName,
                    kana:form.kana,
                    whiteProductName:form.whiteProductName,
                    appVersion: form.appVersion,
                    appPackage: form.appPackage,
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
                if (form.applyTime) {
                    params.lstartTime = form.applyTime[0];
                    params.lendTime = form.applyTime[1];
                }
                return params;
            },
            // 选取订单
            selectionChange(val) {
                this.selectedList = [];
                let arr = val;
                arr.forEach((item) => {
                    this.selectedList.push(item.id);
                });
            },
            // 弹出手动分单弹框
            assignOrder() {
                this.assignOrderDialog.isVisible = true;
            },
            // 取消分单
            cancel() {
                this.assignOrderDialog.isVisible = false;
                this.assignOrderDialog.groupForm.operator = '';
            },
            // 获取预催收员账号列表
            getYCAccount() {
                const params = {
                    isPage: 1,
                    page: {
                        pageNo: 1,
                        pageSize: 10000
                    },
                    roleCode: 141, // 角色类型
                    collectionUserName: '', // 账号类型
                };
                this.$api.authorityManage.queryCollectorsNew(params).then((res) => {
                    const { status, data, error } = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.staffList = data.resultData.filter(item => {
                            return item.active === 0;
                        })
                    }
                });
            },
            submitAssignOrder() {
                const params = {
                    collectionUserId: this.assignOrderDialog.groupForm.operator,
                    ids: this.selectedList.join(',')
                };
                this.$api.authorityManage.changeOverdueInfoYcsCollector(params).then((res) => {
                    const { status, error } = res;
                    if ('1' === status && '00000000' === error) {
                        this.$message.success(this.$t('common.successfulOperation'));
                        this.getTableData();
                        this.assignOrderDialog.isVisible = false;
                    }
                });
            },
            //获取分单开关状态
            getAutoAssignOrderActive() {
                this.$api.collection.getSwitch().then((res) => {
                    const { status, data, error } = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.autoAssignOrde.isOpen = data.ycsSwitchOff === 0 ? true : false;
                        this.autoAssignOrde.id = data.id;
                    }
                });
            },
            //自动分单开关
            changeAutoAssignOrder() {
                this.$confirm(!this.autoAssignOrde.isOpen ? this.$t('common.confirmCloseAssignOrder') : this.$t('common.confirmOpenAssignOrder'), '', {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    const params = {
                        ycsSwitchOff: this.autoAssignOrde.isOpen ===  true ? 0 : 1 ,
                        id: this.autoAssignOrde.id
                    }
                    this.$api.collection.updateSwitch(params).then((res) => {
                        const { status, data, error } = res;
                        if ('1' === status && '00000000' === error) {
                            this.$message.success(this.$t('common.successfulOperation'));
                        }else {
                            this.autoAssignOrde.isOpen = !this.autoAssignOrde.isOpen;
                        }
                    });
                }).catch(() => {
                    this.autoAssignOrde.isOpen = !this.autoAssignOrde.isOpen;
                });
            },
            goDetail(row) {
                this.$openNewBlank(`#/conf/collection/order-manage/order-detail/${row.id}/${row.orderId}/${row.repayStatus}/${row.userId}/${row.repayScheduleId}/yc?appPackage=${row.appPackage}`);
            },
            pageChange(val) {
                this.getTableData({
                    currentPage: val
                });
            },
            handleSizeChange(val) {
                this.page.currentPage = 1;
                this.page.pageSize = val;
                this.getTableData();
            },
        },
        created() {
            this.domain = this.$storage.get('user').domain
            this.showSpread = domain.showSpread();
            this.getTableData();
            this.getYCAccount();
            this.getAutoAssignOrderActive();
        }
    }
</script>
<style lang="scss">
    [data-page=collection-preOrderManage-waitAssign] {
        .el-col {
            padding-left: 10px;
        }
        .el-table .cell, .el-table th > .cell {
            word-break: keep-all;
            word-wrap: break-word;
        }
        .content_panel_top {
            .el-button {
                margin-bottom: 18px
            }
        }
        .pagination {
            margin: 10px 0;
            display: flex;
            justify-content: flex-end;
        }
        .el-radio__label {
            word-break:break-all;
            white-space:pre-wrap
        }
    }
</style>
